package com.salmon.security.app;

import com.salmon.security.core.AppResourceServerConfigurerAdapter;
import com.salmon.security.core.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import com.salmon.security.core.authorization.AuthorizeConfigManager;
import com.salmon.security.core.authorization.impl.AnyRequestAuthenticatedAuthorizeConfigProvider;
import com.salmon.security.core.validate.code.SecurityConstants;
import com.salmon.security.core.validate.code.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.social.security.SpringSocialConfigurer;

/**
 * 资源服务器
 */
@Configuration
@EnableResourceServer
public class SalmonResourceServerConfig extends AppResourceServerConfigurerAdapter {

    @Autowired
    protected AuthenticationSuccessHandler salmonAuthenticationSuccessHandler;

    @Autowired
    protected AuthenticationFailureHandler salmonAuthenticationFailureHandler;

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private SpringSocialConfigurer salmonSocialSecurityConfig;

    @Autowired
    private ValidateCodeSecurityConfig validateCodeSecurityConfig;

    @Autowired
    private AuthorizeConfigManager authorizeConfigManager;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
                .loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
                .successHandler(salmonAuthenticationSuccessHandler)
                .failureHandler(salmonAuthenticationFailureHandler);
       http
               .apply(validateCodeSecurityConfig) // 短信验证码以及图片验证码校验过滤器的配置
               .and()
               .apply(smsCodeAuthenticationSecurityConfig) //短信验证码的认证配置
               .and()
               .apply(salmonSocialSecurityConfig)//Social登录的认证配置
               .and()
               .csrf().disable();
        authorizeConfigManager.config(http.authorizeRequests());
    }

    /**
     * 注入任何请求都需要验证的配置， 注意注入顺序，一定要在所有的实现了AuthorizeConfigProvider接口的类注入之后才能注入
     */
    @Bean
    @Order
    public AnyRequestAuthenticatedAuthorizeConfigProvider anyRequestAuthenticatedAuthorizeConfigProvider(){
        return new AnyRequestAuthenticatedAuthorizeConfigProvider();
    }
}
